package com.example.origin.spider.service;

import com.example.origin.spider.webmagic.ChromeProcessor;
import com.example.origin.spider.webmagic.SimpleChromeDownloader;
import com.example.origin.spider.properties.ProcessorProperties;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.springframework.stereotype.Service;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Request;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;
import java.util.function.Function;

@Slf4j
@Service("wenshu-court")
public final class WenshuCourtProcessor extends ChromeProcessor {

    @Override
    public void process(ResultItems resultItems, Task task) {
        System.out.println("get page: " + resultItems.getRequest().getUrl());
        for (Map.Entry<String, Object> entry : resultItems.getAll().entrySet()) {
            System.out.println(entry.getKey() + ":\t" + entry.getValue());
        }
    }

    @Override
    @SneakyThrows
    public void process(Page page, ProcessorProperties properties) {
        if (page.getUrl().get().contains("ip.chaxunjiao.com")) {
            page.putField("ip", page.getHtml().css("h3").get());
            return;
        }else if(page.getUrl().get().contains("https://wenshu.court.gov.cn/website/wenshu")){
            SimpleChromeDownloader downloader = (SimpleChromeDownloader) page.getRequest().getDownloader();
            WebDriver webDriver = downloader.getWebDriver();
            log.info("标题：{}",webDriver.findElement(By.cssSelector(".PDF_title")).getText());
            log.info("案由：{}",page.getHtml().css(".dftable .text-ellipsis", "text").get());
            log.info("发布日期：{}",page.getHtml().css("table.dftable > tbody > tr:nth-child(2) > td:nth-child(2)", "text").get());
            log.info("法院：{}",page.getHtml().css("div.PDF_pox > div:nth-child(2)", "text").get());
            log.info("案号：{}",page.getHtml().css("#1", "text").get());
            log.info("原告：{}",webDriver.findElement(By.id("2")).getText());
            String text = webDriver.findElement(By.cssSelector(".PDF_pox")).getText();
            String beigao ="";
            String shenpanyuan ="";
            String shenpanriqi ="";
            String[] strings = text.split("\n");
            for (int i = 0; i < strings.length; i++) {
                String s = strings[i];
                if (s.contains("被告：")) {
                    beigao = s;
                }
                if (s.contains("审判员")) {
                    shenpanyuan = s;
                    shenpanriqi = strings[i + 1];
                }
            }
            log.info("被告：{}",beigao);
            log.info("审判员：{}",shenpanyuan);
            log.info("审判日期：{}",shenpanriqi);
            log.info("原文：{}", text);
            return;
        }else if(page.getUrl().get().contains("https://account.court.gov.cn/app#/login")){
            SimpleChromeDownloader downloader = (SimpleChromeDownloader) page.getRequest().getDownloader();
            WebDriver webDriver = downloader.getWebDriver();

            webDriver.findElement(By.cssSelector(".phone-number-input")).sendKeys("18051375815");
            webDriver.findElement(By.cssSelector(".password")).sendKeys("Tai@240613");
            webDriver.findElement(By.cssSelector(".login-button-container .button")).click();
            webDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
            TimeUnit.SECONDS.sleep(5);

            webDriver.get("https://wenshu.court.gov.cn");
            webDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
            TimeUnit.SECONDS.sleep(5);

            webDriver.findElement(By.id("loginLi")).click();
            TimeUnit.SECONDS.sleep(5);

            redoByCondition(webDriver,(driver, flag) -> {
                webDriver.navigate().refresh();
                try {
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            },driver -> webDriver.findElements(By.cssSelector(".search-rightBtn")).isEmpty());

            webDriver.findElement(By.cssSelector(".search-middle .searchKey")).sendKeys("晶科能源股份有限公司");
            webDriver.findElement(By.cssSelector(".search-rightBtn")).click();

            TimeUnit.SECONDS.sleep(5);
            List<WebElement> elements = webDriver.findElements(By.cssSelector(".caseName"));
            for (WebElement element : elements) {
                if (element.getText().contains("晶科能源股份有限公司") && (
                        element.getText().contains("裁决书")||
                        element.getText().contains("判决书")||
                        element.getText().contains("调解书")
                        )) {
                    Request request = new Request();
                    request.setDownloader(downloader);
                    request.setUrl(element.getAttribute("href"));
                    page.addTargetRequest(request);
                }
            }
            return;
        }

        page.addTargetRequest("https://ip.chaxunjiao.com/");
    }

    private static void redoByCondition(WebDriver driver, BiConsumer<WebDriver,Boolean> consumer, Function<WebDriver,Boolean> function) {
        consumer.accept(driver,false);
        Boolean falg = true;
        if (function.apply(driver)) {
            for (int i = 0; i < 10; i++) {
                falg = function.apply(driver);
                if (!falg) {
                    break;
                }
                log.info("【第{}次重新操作】",i+1);
                consumer.accept(driver,true);
            }
        }else {
            falg = false;
        }
        if (falg) {
            // todo 告警
        }
    }

}
